package al21mergeTwoLists;


import java.util.List;

class ListNode {
    int val;
    ListNode next;

    // 构造函数
    ListNode(int val) {
        this.val = val;
        this.next = null;
    }
}

public class MergeTwoLists21 {

    // 打印链表
    public static void printList(ListNode head) {
        ListNode current = head;
        while (current != null) {
            System.out.print(current.val + " ");
            current = current.next;
        }
        System.out.println();
    }

    // 主方法用于测试
    public static void main(String[] args) {
        // 创建两个有序链表
        ListNode l1 = new ListNode(0);
/*        l1.next = new ListNode(2);
        l1.next.next = new ListNode(4);
*//*        l1.next.next.next = new ListNode(7);*/

        ListNode l2 = new ListNode(1);
        l2.next = new ListNode(3);
        l2.next.next = new ListNode(4);
/*        l2.next.next.next = new ListNode(8);
        l2.next.next.next.next = new ListNode(10);
        l2.next.next.next.next.next = new ListNode(11);*/
        // 打印原链表
        System.out.println("List 1:");
        printList(l1);

        System.out.println("List 2:");
        printList(l2);

        // 合并两个链表
        ListNode mergedList = mergeTwoLists(l1, l2);

        // 打印合并后的链表
        System.out.println("Merged List:");
        printList(mergedList);
    }

    private static ListNode mergeTwoLists(ListNode list1, ListNode list2) {

        if (list1 == null ) {
            return list2;
        }
        if (list2 == null) {
            return list1;
        }

        ListNode list = new ListNode(0);
        ListNode cur = list;
        while (list1 != null && list2 != null) {
            if (list1.val < list2.val) {
                cur.next = list1;
                list1=list1.next;
            }else {
                cur.next = list2;
                list2=list2.next;
            }
            cur = cur.next;
        }
        if (list1!=null){
            cur.next = list1;
        }
        if(list2!=null){
            cur.next = list2;
        }

        return list.next;
    }
}
